#include "application.h"
#include "widget.h"

static void myMessageOutput(QtMsgType type, const char *msg);

int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(jslib);
    qInstallMsgHandler(myMessageOutput);
    Application a(QString("yt_front_app_id"), argc, argv);

    if( a.isRunning() ) // すでに実行中チェック
        return !a.sendMessage("実行中のインスタンスに渡す何らかの文字列"); // messageReceivedで受け取る

    Widget w;
    a.setActivationWindow(&w);
    w.show();

    QObject::connect(&a, SIGNAL(messageReceived(const QString&)),
             &w, SLOT(handleMessage(const QString&)));

    return a.exec();
}

#define MSG_UNIT (1024)
static void myMessageOutput(QtMsgType type, const char *msg)
{
    //in this function, you can write the message to any stream!
    switch (type) {
    case QtDebugMsg:
        //fprintf(stderr, "Debug: %s\n", msg);
    {
        size_t v_sizelen = strlen(msg);
        char v_buff[MSG_UNIT+1];
        for(size_t i=0; i<v_sizelen; i+=MSG_UNIT)
        {
            strncpy(v_buff, msg, MSG_UNIT);
            v_buff[MSG_UNIT]= '\0';
            fprintf(stderr, "%s", v_buff);
            fflush(stderr);
            msg += strlen(v_buff);
        }
        fprintf(stderr, "\n");
        fflush(stderr);
    }
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s\n", msg);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s\n", msg);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s\n", msg);
        abort();
    }
}
